using System;
using System.IO;
using System.Windows.Forms;
using CommandLine.Utility;
using Slaks.DocumentSerialization.Dictionary;

namespace Slaks.Dictionary
{
	class DictionaryComparison
	{
		[STAThread]
		static void Main(string[] args)
		{
			try
			{
				const string dictOneParam = "dictOne";
				const string dictTwoParam = "dictTwo";
				DictionaryMap dictionaryOne = null;
				DictionaryMap dictionaryTwo = null;
				Arguments arg = new Arguments(args);
				string fileOne,fileTwo;
				if (arg[dictOneParam] == null) fileOne = ChooseFile("Provide name of the file with the first dictionary");
				else fileOne = arg[dictOneParam];

				if (fileOne == null || File.Exists(fileOne) == false)
				{
					throw new Exception("First file is either not provided or file path is invalid");
				}

				Console.WriteLine(fileOne);

				if (arg[dictTwoParam] == null) fileTwo = ChooseFile("Provide name of the file with the secondt dictionary");
				else fileTwo = arg[dictTwoParam];

				if (fileTwo == null || File.Exists(fileTwo) == false)
				{
					throw new Exception("Second file is either not provided or file path is invalid");
				}

				Console.WriteLine(fileOne);

				dictionaryOne = LoadDictionaryMap(fileOne);
				Console.WriteLine("Dictionary of the first file was loaded");
				dictionaryTwo = LoadDictionaryMap(fileTwo);
				Console.WriteLine("Dictionary of the second file was loaded");

				DoCompare(dictionaryOne,dictionaryTwo);
			}catch(Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			
		}
		static string ChooseFile(string title)
		{
			string file = null;
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.Title = title;
			if (DialogResult.OK == dialog.ShowDialog())
			{
				file = dialog.FileName;
			}
			return file;
		}
		static DictionaryMap LoadDictionaryMap(string file)
		{
			return DictionaryInfo.ReadXml(file);
		}
		static void DoCompare(DictionaryMap one,DictionaryMap two)
		{
			bool isOk = true;
			//iterate through first dictionary
			foreach(long id in one.Keys)
			{
				if (two.Contains(id) == false)
				{
					Console.WriteLine("Id " + id + " doesn't exist in the second dictionary map");
					isOk = false;
				}
			}
			//iterate through second dictionary
			foreach(long id in two.Keys)
			{
				if (one.Contains(id) == false)
				{
					Console.WriteLine("Id " + id + " doesn't exist in the first dictionary map");
					isOk = false;
				}
			}

			if (isOk)
			{
				Console.WriteLine("Two dictionaries are identical");
			}
		}
	}
}
